package com.hzcx.app.simplechat.ui.moment;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.event.CreateMomentEvent;
import com.hzcx.app.simplechat.ui.moment.contract.MomentCreateContract;
import com.hzcx.app.simplechat.ui.moment.event.MomentCreateEvent;
import com.hzcx.app.simplechat.ui.moment.presenter.MomentCreatePresenter;
import com.hzcx.app.simplechat.ui.moment.util.CenterAlignImageSpan;
import com.hzcx.app.simplechat.ui.publicui.LocationActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.event.LocationEvent;
import com.hzcx.app.simplechat.ui.setting.adapter.ImgAdapter;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 发布动态界面
 */
public class MomentCreateActivity extends BaseActivity<MomentCreatePresenter> implements BaseQuickAdapter.OnItemClickListener, OnResultCallbackListener<LocalMedia>,
        BaseQuickAdapter.OnItemChildClickListener, MomentCreateContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.cons_title)
    ConstraintLayout consTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.iv_http)
    ImageView ivHttp;
    @BindView(R.id.tv_visibility)
    TextView tvVisibility;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_location)
    ImageView ivLocation;

    private List<String> imgList;
    private ImgAdapter imgAdapter;
    private List<LocalMedia> seleteImgList;
    private int httpIndex;
    private String httpContent;
    private int visible = 1;
    private String lat;
    private String lng;

    @Override
    public int getLayout() {
        return R.layout.activity_moment_create;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MomentCreatePresenter();
    }

    @Override
    public void initView() {
        seleteImgList = new ArrayList<>();
        imgList = new ArrayList<>();
        imgAdapter = new ImgAdapter(R.layout.rv_item_img, imgList);
        rvImg.setLayoutManager(new GridLayoutManager(this, 3));
        rvImg.setAdapter(imgAdapter);

        imgAdapter.setOnItemClickListener(this);
        imgAdapter.setOnItemChildClickListener(this);
        helper.attachToRecyclerView(rvImg);

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (EmptyUtils.isNotEmpty(httpContent)) {
                    if (etContent.getText().length() <= httpIndex) {
                        httpIndex = -1;
                        httpContent = "";
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void initData() {
        // 添加初始值
        imgList.add("");
        imgAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.iv_photo, R.id.iv_http, R.id.tv_visibility, R.id.tv_commit, R.id.iv_location,R.id.ll_location})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo: // 图片选择
                PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.MULTIPLE, true, false, seleteImgList, this);
                break;

            case R.id.iv_http: // 添加链接
                if (EmptyUtils.isNotEmpty(httpContent)) {
                    showError("每个内容只能添加一个链接");
                    return;
                }
                startActivity(new Intent(this, MomentCreateHttpActivity.class));
                break;

            case R.id.tv_visibility: // 可见性
                showVisibilityDialog();
                break;

            case R.id.tv_commit: // 提交
                if (EmptyUtils.isEmpty(etContent.getText().toString())) {
                    showError("请输入内容");
                    return;
                }
                showLoading();
                mPresenter.upLoadImg(this, imgList);
                break;

            case R.id.iv_location: // 位置
            case R.id.ll_location: // 位置
                registerLocationPermission();
                break;
        }
    }

    /**
     * 获取位置权限
     */
    private void registerLocationPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请失败
     */
    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败，无法保存图片");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        startActivity(new Intent(this, LocationActivity.class));
    }

    /**
     * 图片列表点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (EmptyUtils.isEmpty(imgList.get(position))) {
            PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.MULTIPLE, true, false, seleteImgList, this);
        } else {
            PhotoUtil.openPhoto(this, seleteImgList, position);
        }
    }

    /**
     * 图片选取返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        seleteImgList.clear();
        seleteImgList.addAll(result);
        imgList.clear();
        for (LocalMedia media : result) {
            imgList.add(PhotoUtil.getPath(media));
        }
        if (imgList.size() < 9) {
            imgList.add(imgList.size(), "");
        }
        imgAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCancel() {

    }

    /**
     * 子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_delete:
                deleteImg(position);
                break;
        }
    }

    /**
     * 删除图片
     *
     * @param pos
     */
    private void deleteImg(int pos) {
        seleteImgList.remove(pos);
        imgList.remove(pos);
        if (EmptyUtils.isNotEmpty(imgList.get(imgList.size() - 1))) {
            imgList.add(imgList.size(), "");
        }
        imgAdapter.notifyDataSetChanged();
    }

    /**
     * 添加内容返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addContent(CreateMomentEvent event) {
        if (event.getTag() == CreateMomentEvent.HTTP) {
            int length = etContent.getText().length();
            httpIndex = etContent.getText().length();
            httpContent = event.getContent();
            SpannableString sps = new SpannableString(etContent.getText().toString() + "网页链接");
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_icon_moment_http_text);
            drawable.setBounds(0, 0, DpUtils.dp2px(this, 80), DpUtils.dp2px(this, 15));
            //居中对齐imageSpan
            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
            sps.setSpan(imageSpan, length, length + 4, ImageSpan.ALIGN_BASELINE);
            etContent.setText(sps);
            etContent.setSelection(etContent.length());//将光标移至文字末尾
        }
    }

    /**
     * 可见性弹窗
     */
    private void showVisibilityDialog() {
        List<String> list = new ArrayList<>();
        list.add("互为好友可见");
        list.add("仅自己可见");
        PublicRoundDialog roundDialog = new PublicRoundDialog(this, list, (pos, menu) -> {
            switch (menu) {
                case "互为好友可见":
                    tvVisibility.setText("好友可见");
                    visible = 1;
                    break;

                case "仅自己可见":
                    tvVisibility.setText("仅自己");
                    visible = 2;
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 图片上传成功
     *
     * @param url
     */
    @Override
    public void upLoadSuccess(String url) {
        String content;
        if (EmptyUtils.isEmpty(httpContent)) {
            content = etContent.getText().toString();
        } else {
            content = etContent.getText().toString().substring(0, httpIndex) +
                    etContent.getText().toString().substring(httpIndex + 4);
        }
        LogUtils.d("content:" + content);
        mPresenter.commitMoment(this, content, url, visible, httpContent, httpIndex, lng, lat, tvAddress.getText().toString());
    }

    /**
     * 动态发布成功
     */
    @Override
    public void commitSuccess() {
        EventBus.getDefault().post(new MomentCreateEvent());
        showError("发布成功");
        finish();
    }

    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFrlg, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //滑动事件  下面注释的代码，滑动后数据和条目错乱，被舍弃
//            Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//            ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(imgList, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(imgList, i, i - 1);
                }
            }
            imgAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            imgAdapter.notifyDataSetChanged();  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    });

    /**
     * 地址选择
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectLocation(LocationEvent event) {
        lat = event.getLat() == 0 ? null : String.valueOf(lat);
        lng = event.getLng() == 0 ? null : String.valueOf(lng);
        tvAddress.setText(event.getAddress());
    }
}
